// pages/reviewRecord/essay/essay.js

//获取应用实例
const app = getApp();
let tool = require('../../../utils/tool.js');
const httpUtils = require('../../../utils/httpUtils.js');
const bgMusic = wx.getBackgroundAudioManager()
var WxParse = require('../../../wxParse/wxParse.js');
const audio = require('../../../utils/audio.js');
//  正在录音的下标
let recordingIndex = 0;


Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    essay: {},
    phrase: [],
    sentence: [],
    innerAudioContext: new Object(),
    is_show_esasy:1, //0不显示英文原文，1显示
    is_show_translate: 0, //0不显示翻译  1显示
    is_class_pic: 0, //是否有课堂训练图片，默认0没有，1有
    essay_id: 1, //范文id
    // isOpen: false, //播放开关
    // starttime: "00:00", //正在播放时长
    // duration: '00:00', // 总时长
    // offset: 0, //记录播放的seek
    src: "https://yixuepai-media.oss-cn-beijing.aliyuncs.com/Public/uploads/Picture/2018-07-21/5b52df801b860.mp3", //音频的地址
    requiretext: "假定你是李华，正在一所英国学校学习暑期课程，遇到一些困难，希望得到学校辅导中心(Learning Center)的帮助。根据学校规定，你需要书面预约，请按下列的要求写一封信：1.本人简介 2.求助内容 3.约定时间 4.你的联系方式(Email: lihua@1236.com ; Phone:12345678)注意事项： 1.词数90词左右 2.文中不能出现真实的人名。", //题目要求
    flag: true, //提示弹窗的标志
    showVipModal: false, //开通vip弹窗组件是否显示
    isVip: false, //vip为	0 游客 1 VIP
    hasreview: 0, //0未复习，1已提交复习
    has_read: 1, //0无读一遍，1有读一遍
    hasRecord: 0, //0未录音，1有录音
    source: 0, //0是学习记录进入的，1是复习进入的
    task_id: '', //任务id
    sort: '14', //类别,写作读一遍
    voice: '',//自己录音的路径
    score: '-1',//语音识别的分数
    btnPlayStatus: [], //语音识别的三个按钮的状态
    can_submit: 1, //1 可以提交 0不可以提交
    uservoicetemp:"", //自己的录音上传后的路径
    status:0,
    showRecordModal: false,
    scrollTop:-1, //滚动的距离
    toView:"",//跳转的索引,这哥们必须动态更改才可以使滑动生效
    scroll_height:800,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let windowHeight = wx.getSystemInfoSync().windowHeight // 屏幕的高度
    let windowWidth = wx.getSystemInfoSync().windowWidth // 屏幕的宽度
    //判断一下从学习记录进的还是从复习进入的
    if (options.source) {
      that.setData({
        source: options.source
      })
    }
 
      that.setData({
        task_id: options.task_id,
        has_read: 1,
        can_submit: options.can_submit,
        status:options.status,
        scroll_height:windowHeight*750/windowWidth-320-30,
      })
      console.log("height="+that.data.scroll_height)
      //获取复习数据
      that.getEssayReview();
 
  },
  /**
   * 获取范文详情
   */
  getEssayDetail: function () {
    let that = this;
    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.getessaydetail({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      id: that.data.essay_id,
    }).then((res) => {
      //课堂训练图片的url,为空则表示没有，隐藏
      let temurl = res.data.pic;
      let last_writing = 0;
      if (!temurl) {
        last_writing = 0;
      } else {
        last_writing = 1;
      }
      that.setData({
        essay: res.data,
        phrase: res.data.phrase,
        sentence: res.data.sentence,
        src: res.data.essay_url,
        is_class_pic: last_writing,
      })
      WxParse.wxParse('article', 'html', res.data.essay, that, 5)
      WxParse.wxParse('translate', 'html', res.data.translate, that, 5)
      WxParse.wxParse('require', 'html', res.data.require, that, 5)

     
    });
  },


  //获取复习数据
  getEssayReview() {
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true
    })

    httpUtils.getEssayReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      sort: that.data.sort,
    }).then((res) => {

      that.setData({
        essay: res.data.content,
        phrase: res.data.goodswords,
        sentence: res.data.sentence,
        is_class_pic: 0,
        voice:res.data.voice,
        score:res.data.score
      })
      WxParse.wxParse('article', 'html', res.data.content.essay, that, 5)
      WxParse.wxParse('translate', 'html', res.data.content.translate, that, 5)
      WxParse.wxParse('require', 'html', res.data.content.require, that, 5)

       //如果有读一遍，初始化一下audio
       let len = 1;
       that.setData({
         btnPlayStatus: audio.initAudioBtn(len, len)
       })
       audio.onEnded({
         callback(data) {
           that.setData({
             btnPlayStatus: data
           })
         }
       });
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setData({
      isVip: (app.globalData.studentInfo.is_vip == 1 ? true : false)
    })
  },



  /**
   *点击底部题目要求
   */
  showRequirePop: function () {
    let that = this;
    that.setData({
      flag: false, //弹出题目要求框
    })

  },

  /**关闭modal弹窗 */
  closeMask: function () {
    this.setData({
      flag: true
    })
  },

  //查看或隐藏原文
  lookEssay:function(){
    let that =this;
    let is_show_esasy =that.data.is_show_esasy;
    if(is_show_esasy==0){
       that.setData({
         is_show_esasy:1,
       })
    }else if(is_show_esasy ==1){
      that.setData({
        is_show_esasy:0,
      })
    }
  },

  /**
   * 查看翻译
   */
  lookTranslate: function () {
    let that = this;
    let is_show_translate = this.data.is_show_translate;
    if (is_show_translate == 0) {
      //必须改成，先显示，然后再滚动，分两次折行setData,否则会导致scroll-into-view失效
      that.setData({
        is_show_translate: 1,
        // scrollTop:900,
      })
     that.setData({
       toView:"zhongwen",
     })
    } else if (is_show_translate == 1) {
      that.setData({
        is_show_translate: 0,
        // scrollTop:0,
      })
      that.setData({
        toView:"yingwen",
      })
    }

  },



  // 查看课堂训练的大图
  lookpicutre: function () {
    let that = this;
    //修改本句的imgurl为上次的仿写地址即可
    let imgUrl = that.data.essay.pic;
    //在新界面预览样例大图
    wx.previewImage({
      current: imgUrl,
      urls: [imgUrl],
    })
  },

  // 播放音频
  playAudio(event) {
    var that = this;
    var type = event.currentTarget.dataset.type;
    var index = event.currentTarget.dataset.index;
    console.log("type=" + type + ",index=" + index)

    audio.play({
      type: type,
      index:0,
      audiosrc: event.currentTarget.dataset.audiosrc,
      callback(data) {
        that.setData({
          btnPlayStatus: data,
        });
      }
    });
  },


  //  录音并打分
  recordScore: function (event) {
    var that = this;
    recordingIndex = event.currentTarget.dataset.index;
    that.setData({
      showRecordModal: true,
      is_show_esasy:0,
      originalStr: event.currentTarget.dataset.originalstr
    });
    audio.stop({
      callback(data) {
        that.setData({
          btnPlayStatus: data,
        });
      }
    });
    console.log("originalStr:" + that.data.originalStr)
  },

  // 录音成功
  recordSuccess: function (res) {
    var that = this;
    console.log("录音成功" + JSON.stringify(res))
    that.setData({
      showRecordModal: false,
      is_show_esasy:1
    });
    let score = res.detail.score;
    console.log("score=" + score)
    let tempFilePath = res.detail.tempFilePath;
    if (score < 0) {
      wx.showToast({
        title: '没有听清~',
        icon: 'none',
        duration: 2000
      });
    } else {
      that.setData({
        voice: tempFilePath,
        score: score
      })

      let bodyParam = {
        access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
        type: tempFilePath,
      }
      let rs = tool.getSign(bodyParam, getApp().globalData.key);
      let tempurl = getApp().globalData.apiURL + 'common/upload?sign=' + rs.sign;
      console.log(tempurl)
      wx.uploadFile({
        url: tempurl,
        filePath: tempFilePath,
        name: 'file',
        formData: {
          'word':that.data.essay_id,
          'sub_vedio': tempFilePath,
          'type':'wx_voice',
        },
        success(res) {
          console.log("录音上传成功")
          let result = JSON.parse(res.data);
          let path = result.data.path;
          console.log(path)
          that.setData({
            uservoicetemp: path
          })
          
        },

      })

    }
  },

//是否确认提交对话框
  showSubmitDialog(){
    let that =this;
    console.log("点击了提交按钮")
    if(that.data.showRecordModal){
      console.log("正在录音")
     return;
    }

    if (that.data.score < 0) {
      wx.showToast({
        title: '请先录音后再提交',
        icon: 'none',
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否确定提交',
      success(res) {
        if (res.confirm) {
          that.setData({
            showRecordModal:false
          })
          that.submitReview();
        } else if (res.cancel) {
          console.log("点击了取消") 
        }
      }
    })

  },



  //提交复习
  submitReview() {
    let that = this;
    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    httpUtils.submitRWReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      id: that.data.essay.id,
      question_type: 4,  //1 阅读 4 写作
      sort: that.data.sort,
      pic: "", //拍照图片地址
      voice: that.data.uservoicetemp,//录音文件地址
      score: that.data.score, //语音识别的分数
    }).then((res) => {
      wx.hideLoading();
      wx.showToast({
        title: '作业提交成功~',
        icon: 'success',
        duration: 1000
      })

      setTimeout(function () {
        wx.navigateBack({
          delta: -1
        })
      }, 1000)
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this;
    audio.destory();
  },

  /**
   * 生命周期函数--监听页面卸载
   * 页面卸载时停止播放
   */
  onUnload: function () {
    let that =this;
    audio.destory();
    that.setData({
      showRecordModal:false
    })

    console.log("离开界面")
   
  },

  /**点击组件弹窗中的开通vip按钮 */
  goOpen: function () {
    wx.navigateTo({
      url: "/pages/vip/vipBuy",
    });
    this.setData({
      showVipModal: false,
    })
  },

 
})